/*
 * @Author: 耿远风
 * @Date: 2020-10-16 14:32:30
 * @LastEditors: 耿远风
 * @LastEditTime: 2020-10-16 14:32:48
 * @Description: 
 */

import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
import * as express from 'express';
import * as dayjs from 'dayjs';

@Catch()
export class AnyExceptionFilter implements ExceptionFilter {
    catch(exception: any, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const res: express.Response = ctx.getResponse();
        const req: express.Request = ctx.getRequest();

        if (exception && exception.name == 'GlobalError') {
            console.error(exception);
            return res.json({
                code: 1,
                error: exception.message,
                globalError: true,
            });
        }

        if (exception && exception.getStatus && exception.getStatus() == 404) {
            console.error('404 NOT FOUND', req.originalUrl);
        } else if (exception instanceof Error) {
            // 没有被try-catch包裹的Mongoose错误
            console.error(exception);
            return res.json({
                code: 1,
                error: exception.message,
                globalError: true,
            });
        } else {
            if (
                exception &&
                exception.message &&
                typeof exception.message === 'string' &&
                exception.message.startsWith(
                    'Cast to ObjectId failed for value',
                )
            ) {
                console.error(exception.message);
            } else {
                console.error(exception);
            }
            if (req) {
                console.error(
                    `Error At Url: ${req.originalUrl} body:${JSON.stringify(
                        req.body,
                    ).slice(0, 100)} query: ${JSON.stringify(req.query).slice(
                        0,
                        100,
                    )}`,
                );
            }
            if (!exception || !exception.getStatus || !res) return;
        }

        res.json({
            statusCode: exception.getStatus(),
            timestamp: dayjs().format('YYYY-MM-DD hh:MM:ss:SSS'),
            path: req.url,
        });
    }
}
